import os
import subprocess
import json

def get_audio_codec(file_path):
    """获取视频文件的音频编码格式"""
    cmd = [
        'ffprobe',
        '-v', 'quiet',
        '-print_format', 'json',
        '-show_streams',
        '-select_streams', 'a',
        file_path
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    try:
        info = json.loads(result.stdout)
        if 'streams' in info and len(info['streams']) > 0:
            return info['streams'][0].get('codec_name', 'unknown')
        return 'unknown'
    except json.JSONDecodeError:
        return 'unknown'

def convert_ac3_to_aac(input_file, output_file):
    """将AC3音频转换为AAC格式"""
    cmd = [
        'ffmpeg',
        '-i', input_file,
        '-c:v', 'copy',  # 保持视频流不变
        '-c:a', 'aac',   # 转换为AAC音频
        '-b:a', '192k',  # 设置音频比特率
        '-y',            # 覆盖输出文件
        output_file
    ]
    subprocess.run(cmd, check=True)

def process_directory(directory):
    """处理目录中的所有MP4文件"""
    for filename in os.listdir(directory):
        if filename.endswith('.mp4') and not filename.startswith('.'):
            file_path = os.path.join(directory, filename)
            codec = get_audio_codec(file_path)
            
            if codec.lower() == 'ac3':
                print(f'发现AC3音频文件: {filename}')
                output_dir = os.path.join(directory, '../ac3_to_aac')
                if not os.path.exists(output_dir):
                    os.makedirs(output_dir)
                output_file = os.path.join(output_dir, f'ac3_to_aac_{filename}')
                print(f'正在转换为AAC格式...')
                convert_ac3_to_aac(file_path, output_file)
                print(f'转换完成: {output_file}')
            else:
                print(f'跳过非AC3音频文件: {filename} ({codec})')

if __name__ == '__main__':
    mp4_directory = '/Users/yawn/Geil/电影/'
    if os.path.isdir(mp4_directory):
        process_directory(mp4_directory)
        print('所有文件处理完成!')
    else:
        print('错误: 指定的目录不存在')